home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 9470 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.3 KB

  1. Path: accursio.comune.bologna.it!usenet
  2. From: Enrico Persiani <vos0225@iperbole.bologna.it>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: malloc question
  5. Date: Sun, 10 Mar 1996 19:00:15 +0100
  6. Organization: Progetto Iperbole - Comune di Bologna - Italy
  7. Message-ID: <314318AF.30F@iperbole.bologna.it>
  8. References: <4htonk$350@news.hklink.net> <4huctt$arv@sparcserver.lrz-muenchen.de>
  9. NNTP-Posting-Host: itiav.comune.bologna.it
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0GoldB1 (Win95; I)
  14. CC: vos0225@iperbole.bologna.it
  15.  
  16. Kurt Watzka wrote:
  17. > alex@station.net (Alex Chu) writes:
  18. > >Hi everybody,
  19. > >I have a question for the following snip C program.
  20. > >typedef struct item {
  21. > >  int val;
  22. > >  struct item *next;
  23. > >} ITEM, *PITEM;
  24. > >main()
  25. > >{
  26. > >  PITEM head, current;
  27. > >  head=(PITEM) malloc(sizeof(ITEM));
  28. > >            ^^^^^^^
  29. > >  head->val=1;
  30. > >}
  31. > >I want to know why need to use the type casting PITEM in front of the
  32. > >malloc ?  Please help!
  33. > Simple answer: You don't have to use that cast, and you should _not_ use
  34. > it, because all you can do with that cast is _hide_ an error.Error?!? Why do you think that casting is an error? The standard ANSI runtime library says:
  35. ...
  36.  
  37. malloc Function
  38.  
  39. Syntax
  40.   #include <stdlib.h>
  41.  
  42.   void *malloc(size_t size);
  43.  
  44. Description
  45.   The 'malloc' function allocates an amount of memory that equals to 'size'.
  46.  
  47. Return values
  48.   The 'malloc' function returns a NULL pointer if it fails, otherwise it returns
  49.   a 'void' pointer to the allocated memory area.
  50. ...
  51.  
  52. So, if he needs to use that pointer returned by malloc function he have to convert it from a 'void' pointer to a 'item' pointer ( PITEM ).
  53. Many compilers don't need the use of casting. It's only a good programming style. But remember: malloc returns a 'void' pointer because it doesn't know wich 
  54. kind of data you'll store in the allocated mem block!
  55.  
  56. > OTOH, if you are using a C++ compiler to translate C programs, the cast
  57. > is needed, but malloc() is obsolete.
  58. > C++ compilers are more rigorous! But if you write a strict-ANSI C program a c++ compiler won't return any error...
  59.  
  60. -- 
  61. Enrico Persiani
  62. Computer Science Student
  63.  
  64. e-mail:  vos0225@iperbole.bologna.it
  65. address: Via A. Saffi 6
  66.          Bologna (BO), 40131
  67.          ITALY
  68.